﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Caching;
using System.Data;

namespace teacher.Util
{
    public class AppAuthorizeAttribute : AuthorizeAttribute
    {
       protected override void HandleUnauthorizedRequest(AuthorizationContext context)
       {
            string name = Users;
            if ("Login|getVersions".Contains(name))
            {
                return;
            }
            string token = context.HttpContext.Request.Params.Get("token");

            if (string.IsNullOrEmpty(token)) {
                context.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
                context.Result = new JsonpResult<object>(new { code = 0, msg = "身份非法,请重新登录" }, context.HttpContext.Request);
                return;
              
            }
            if (System.Web.HttpRuntime.Cache[token] == null)
            {
                DataTable dt = DbHelper.ExecuteDataTable(string.Format("select * from t_token where token='{0}'",token));
                if (dt.Rows.Count == 0)
                {
                    context.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
                    context.Result = new JsonpResult<object>(new { code = 0, msg = "身份非法,请重新登录" }, context.HttpContext.Request);
                }
                else {
                    DataTable tearcher = DbHelper.ExecuteDataTable(string.Format("select * from t_teacher where id='{0}'", dt.Rows[0]["t_id"]));
                    System.Web.HttpRuntime.Cache.Add(token, tearcher, null, DateTime.Now.AddDays(1), TimeSpan.Zero, CacheItemPriority.Normal, null);
                }
            }
        } 
    }
}
